package com.deliveryservicesystem.service.crud.impl;

import com.deliveryservicesystem.app.exceptions.NonexistentEntityException;
import com.deliveryservicesystem.app.exceptions.PreexistingEntityException;
import com.deliveryservicesystem.dataaccess.PersistenceDbManager;
import com.deliveryservicesystem.model.Delivery;
import com.deliveryservicesystem.model.Driver;
import com.deliveryservicesystem.service.crud.DriverCrudService;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 * File Name: DriverCrudServiceImpl.java
 * Version:
 * Description:
 * Package: com.deliveryservicesystem.service.crud.impl
 * Author: Lance
 * Date: Jun 20, 2012
 * Editor:
 */
public class DriverCrudServiceImpl implements DriverCrudService
{

    private static final long serialVersionUID = 1L;
    private EntityManagerFactory emf = null;

    /**
     * Create the new CRUD service. Internally setting the EntityManagerFactory
     * using database details from database properties
     */
    public DriverCrudServiceImpl()
    {
        PersistenceDbManager persistenceManager = PersistenceDbManager.getInstance();
        this.emf = persistenceManager.getEntityManagerFactory();
    }

    @Override
    public EntityManager getEntityManager()
    {
        return emf.createEntityManager();
    }

    @Override
    public void create(Driver driver) throws PreexistingEntityException, Exception
    {
        if (driver.getDeliveryList() == null)
        {
            driver.setDeliveryList(new ArrayList<Delivery>());
        }
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Delivery> attachedDeliveryList = new ArrayList<>();
            for (Delivery deliveryListDeliveryToAttach : driver.getDeliveryList())
            {
                deliveryListDeliveryToAttach = em.getReference(deliveryListDeliveryToAttach.getClass(), deliveryListDeliveryToAttach.getDeliveryNo());
                attachedDeliveryList.add(deliveryListDeliveryToAttach);
            }
            driver.setDeliveryList(attachedDeliveryList);
            em.persist(driver);
            for (Delivery deliveryListDelivery : driver.getDeliveryList())
            {
                Driver oldDriverNoOfDeliveryListDelivery = deliveryListDelivery.getDriverNo();
                deliveryListDelivery.setDriverNo(driver);
                deliveryListDelivery = em.merge(deliveryListDelivery);
                if (oldDriverNoOfDeliveryListDelivery != null)
                {
                    oldDriverNoOfDeliveryListDelivery.getDeliveryList().remove(deliveryListDelivery);
                    oldDriverNoOfDeliveryListDelivery = em.merge(oldDriverNoOfDeliveryListDelivery);
                }
            }
            em.getTransaction().commit();
        }
        catch (Exception ex)
        {
            if (findById(driver.getDriverNo()) != null)
            {
                throw new PreexistingEntityException("Driver " + driver + " already exists.", ex);
            }
            throw ex;
        }
        finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    @Override
    public void edit(Driver driver) throws NonexistentEntityException, Exception
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Driver persistentDriver = em.find(Driver.class, driver.getDriverNo());
            List<Delivery> deliveryListOld = persistentDriver.getDeliveryList();
            List<Delivery> deliveryListNew = driver.getDeliveryList();
            List<Delivery> attachedDeliveryListNew = new ArrayList<>();
            for (Delivery deliveryListNewDeliveryToAttach : deliveryListNew)
            {
                deliveryListNewDeliveryToAttach = em.getReference(deliveryListNewDeliveryToAttach.getClass(), deliveryListNewDeliveryToAttach.getDeliveryNo());
                attachedDeliveryListNew.add(deliveryListNewDeliveryToAttach);
            }
            deliveryListNew = attachedDeliveryListNew;
            driver.setDeliveryList(deliveryListNew);
            driver = em.merge(driver);
            for (Delivery deliveryListOldDelivery : deliveryListOld)
            {
                if (!deliveryListNew.contains(deliveryListOldDelivery))
                {
                    deliveryListOldDelivery.setDriverNo(null);
                    deliveryListOldDelivery = em.merge(deliveryListOldDelivery);
                }
            }
            for (Delivery deliveryListNewDelivery : deliveryListNew)
            {
                if (!deliveryListOld.contains(deliveryListNewDelivery))
                {
                    Driver oldDriverNoOfDeliveryListNewDelivery = deliveryListNewDelivery.getDriverNo();
                    deliveryListNewDelivery.setDriverNo(driver);
                    deliveryListNewDelivery = em.merge(deliveryListNewDelivery);
                    if (oldDriverNoOfDeliveryListNewDelivery != null && !oldDriverNoOfDeliveryListNewDelivery.equals(driver))
                    {
                        oldDriverNoOfDeliveryListNewDelivery.getDeliveryList().remove(deliveryListNewDelivery);
                        oldDriverNoOfDeliveryListNewDelivery = em.merge(oldDriverNoOfDeliveryListNewDelivery);
                    }
                }
            }
            em.getTransaction().commit();
        }
        catch (Exception ex)
        {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0)
            {
                Integer id = driver.getDriverNo();
                if (findById(id) == null)
                {
                    throw new NonexistentEntityException("The driver with id " + id + " no longer exists.");
                }
            }
            throw ex;
        }
        finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    @Override
    public void destroy(Integer id) throws NonexistentEntityException
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Driver driver;
            try
            {
                driver = em.getReference(Driver.class, id);
                driver.getDriverNo();
            }
            catch (EntityNotFoundException enfe)
            {
                throw new NonexistentEntityException("The driver with id " + id + " no longer exists.", enfe);
            }
            List<Delivery> deliveryList = driver.getDeliveryList();
            for (Delivery deliveryListDelivery : deliveryList)
            {
                deliveryListDelivery.setDriverNo(null);
                deliveryListDelivery = em.merge(deliveryListDelivery);
            }
            em.remove(driver);
            em.getTransaction().commit();
        }
        finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    @Override
    public List<Driver> findEntities()
    {
        return findDriverEntities(true, -1, -1);
    }

    @Override
    public List<Driver> findEntities(int maxResults, int firstResult)
    {
        return findDriverEntities(false, maxResults, firstResult);
    }

    private List<Driver> findDriverEntities(boolean all, int maxResults, int firstResult)
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Driver.class));
            Query q = em.createQuery(cq);
            if (!all)
            {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        }
        finally
        {
            em.close();
        }
    }

    @Override
    public Driver findById(Integer id)
    {
        EntityManager em = getEntityManager();
        try
        {
            return em.find(Driver.class, id);
        }
        finally
        {
            em.close();
        }
    }

    @Override
    public int count()
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Driver> rt = cq.from(Driver.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        }
        finally
        {
            em.close();
        }
    }
}
